<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { getNewsById } from "@/api/news";
import {
  NewsStatus,
  NewsStatusText,
  getCategoryName,
  getStatusTagType
} from "../utils/types";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import ArrowLeft from "@iconify-icons/ep/arrow-left";
import EditPen from "@iconify-icons/ep/edit-pen";
import View from "@iconify-icons/ep/view";
import Calendar from "@iconify-icons/ep/calendar";
import User from "@iconify-icons/ep/user";
import Document from "@iconify-icons/ep/document";
import Star from "@iconify-icons/ep/star";
import Top from "@iconify-icons/ep/top";
import ChatDotRound from "@iconify-icons/ep/chat-dot-round";
import dayjs from "dayjs";

defineOptions({
  name: "NewsDetail"
});

const route = useRoute();
const router = useRouter();
const loading = ref(true);

// 资讯详情数据
const newsDetail = reactive({
  id: null,
  title: "",
  categoryId: 1,
  tags: [],
  coverImage: "",
  summary: "",
  content: "",
  author: "",
  source: "",
  status: 0,
  isTop: false,
  isRecommend: false,
  sort: 0,
  viewCount: 0,
  likeCount: 0,
  commentCount: 0,
  publishTime: "",
  createTime: "",
  updateTime: "",
  remark: ""
});

// 生成模拟详情数据
function generateMockDetail(id: string | number) {
  const mockTags = ["热门", "推荐", "精选"];
  const mockAuthors = ["张三", "李四", "王五", "赵六"];
  const mockSources = ["原创", "新华网", "人民网", "央视网"];
  
  return {
    id: Number(id),
    title: `精彩资讯标题 ${id} - 2024年乒乓球世界杯即将开赛`,
    categoryId: Math.floor(Math.random() * 6) + 1,
    tags: mockTags.slice(0, Math.floor(Math.random() * 3) + 1),
    coverImage: `https://picsum.photos/800/400?random=${id}`,
    summary: "这是一条关于乒乓球世界杯的重要资讯，介绍了比赛的最新动态和相关信息。本次比赛将汇聚全球顶尖选手，为观众带来精彩的比赛。",
    content: `
      <h2>资讯详细内容</h2>
      <p>这是资讯ID为 ${id} 的详细内容。2024年乒乓球世界杯即将在上海举行，这是一场备受瞩目的国际赛事。</p>
      
      <h3>比赛亮点</h3>
      <ul>
        <li>汇聚全球顶尖选手</li>
        <li>采用最新的比赛规则</li>
        <li>提供高清直播服务</li>
        <li>设置丰厚的奖金池</li>
      </ul>
      
      <h3>参赛选手</h3>
      <p>本次比赛将有来自30多个国家和地区的优秀选手参与，包括多位世界冠军和奥运冠军。</p>
      
      <h3>比赛安排</h3>
      <p>比赛将持续一周时间，分为男单、女单、男双、女双和混双五个项目。每个项目都将进行激烈的角逐。</p>
      
      <h3>观赛指南</h3>
      <p>观众可以通过多种方式观看比赛：</p>
      <ol>
        <li>现场购票观看</li>
        <li>电视直播</li>
        <li>网络直播平台</li>
        <li>移动端APP</li>
      </ol>
      
      <p>更多详细信息请关注官方网站和社交媒体账号。</p>
    `,
    author: mockAuthors[Math.floor(Math.random() * mockAuthors.length)],
    source: mockSources[Math.floor(Math.random() * mockSources.length)],
    status: Math.floor(Math.random() * 3),
    isTop: Math.random() > 0.7,
    isRecommend: Math.random() > 0.6,
    sort: Math.floor(Math.random() * 100),
    viewCount: Math.floor(Math.random() * 10000) + 1000,
    likeCount: Math.floor(Math.random() * 1000) + 100,
    commentCount: Math.floor(Math.random() * 500) + 50,
    publishTime: dayjs().subtract(Math.floor(Math.random() * 30), "day").format("YYYY-MM-DD HH:mm:ss"),
    createTime: dayjs().subtract(Math.floor(Math.random() * 60), "day").format("YYYY-MM-DD HH:mm:ss"),
    updateTime: dayjs().subtract(Math.floor(Math.random() * 10), "day").format("YYYY-MM-DD HH:mm:ss"),
    remark: `这是资讯 ${id} 的备注信息`
  };
}

// 获取资讯详情
async function fetchNewsDetail() {
  try {
    loading.value = true;
    const id = route.params.id as string;
    
    // 模拟API调用
    const mockData = generateMockDetail(id);
    Object.assign(newsDetail, mockData);
    
    // 实际开发中使用真实API
    // const { data } = await getNewsById(id);
    // Object.assign(newsDetail, data);
  } catch (error) {
    console.error("获取资讯详情失败:", error);
    ElMessage.error("获取资讯详情失败");
  } finally {
    loading.value = false;
  }
}

// 返回列表
function goBack() {
  router.push("/news/list");
}

// 编辑资讯
function editNews() {
  router.push(`/news/form/${newsDetail.id}`);
}

// 获取优先级标签
function getPriorityInfo() {
  if (newsDetail.isTop) {
    return { text: "置顶", type: "danger" };
  }
  if (newsDetail.isRecommend) {
    return { text: "推荐", type: "warning" };
  }
  return null;
}

onMounted(() => {
  fetchNewsDetail();
});
</script>

<template>
  <div class="main" v-loading="loading">
    <!-- 头部操作栏 -->
    <div class="header-actions mb-4">
      <el-button
        type="primary"
        :icon="useRenderIcon(ArrowLeft)"
        @click="goBack"
      >
        返回列表
      </el-button>
      <el-button
        type="success"
        :icon="useRenderIcon(EditPen)"
        @click="editNews"
      >
        编辑资讯
      </el-button>
    </div>

    <!-- 资讯详情卡片 -->
    <el-card class="news-detail-card" shadow="never">
      <!-- 资讯标题和基本信息 -->
      <div class="news-header mb-6">
        <h1 class="news-title mb-4">{{ newsDetail.title }}</h1>
        
        <div class="news-meta flex flex-wrap items-center gap-4 mb-4">
          <div class="meta-item flex items-center">
            <el-icon class="mr-1"><User /></el-icon>
            <span>作者：{{ newsDetail.author || '未知' }}</span>
          </div>
          <div class="meta-item flex items-center">
            <el-icon class="mr-1"><Document /></el-icon>
            <span>来源：{{ newsDetail.source || '未知' }}</span>
          </div>
          <div class="meta-item flex items-center">
            <el-icon class="mr-1"><Calendar /></el-icon>
            <span>发布时间：{{ newsDetail.publishTime || '未发布' }}</span>
          </div>
        </div>

        <div class="news-tags-status flex flex-wrap items-center gap-2 mb-4">
          <!-- 分类标签 -->
          <el-tag type="primary" size="small">
            {{ getCategoryName(newsDetail.categoryId) }}
          </el-tag>
          
          <!-- 状态标签 -->
          <el-tag :type="getStatusTagType(newsDetail.status)" size="small">
            {{ NewsStatusText[newsDetail.status] }}
          </el-tag>
          
          <!-- 优先级标签 -->
          <el-tag
            v-if="getPriorityInfo()"
            :type="getPriorityInfo()?.type"
            size="small"
          >
            <el-icon class="mr-1">
              <Top v-if="newsDetail.isTop" />
              <Star v-else-if="newsDetail.isRecommend" />
            </el-icon>
            {{ getPriorityInfo()?.text }}
          </el-tag>
          
          <!-- 内容标签 -->
          <el-tag
            v-for="tag in newsDetail.tags"
            :key="tag"
            type="info"
            size="small"
          >
            {{ tag }}
          </el-tag>
        </div>

        <!-- 统计信息 -->
        <div class="news-stats flex items-center gap-6 text-sm text-gray-500">
          <div class="stat-item flex items-center">
            <el-icon class="mr-1"><View /></el-icon>
            <span>阅读 {{ newsDetail.viewCount }}</span>
          </div>
          <div class="stat-item flex items-center">
            <el-icon class="mr-1"><Star /></el-icon>
            <span>点赞 {{ newsDetail.likeCount }}</span>
          </div>
          <div class="stat-item flex items-center">
            <el-icon class="mr-1"><ChatDotRound /></el-icon>
            <span>评论 {{ newsDetail.commentCount }}</span>
          </div>
        </div>
      </div>

      <!-- 封面图片 -->
      <div v-if="newsDetail.coverImage" class="news-cover mb-6">
        <img
          :src="newsDetail.coverImage"
          :alt="newsDetail.title"
          class="cover-image"
        />
      </div>

      <!-- 资讯摘要 -->
      <div v-if="newsDetail.summary" class="news-summary mb-6">
        <h3 class="section-title mb-3">资讯摘要</h3>
        <div class="summary-content p-4 bg-gray-50 rounded-lg">
          {{ newsDetail.summary }}
        </div>
      </div>

      <!-- 资讯内容 -->
      <div class="news-content mb-6">
        <h3 class="section-title mb-3">资讯内容</h3>
        <div class="content-body" v-html="newsDetail.content"></div>
      </div>

      <!-- 其他信息 -->
      <div class="news-extra-info">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">排序值：</span>
              <span class="info-value">{{ newsDetail.sort }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">创建时间：</span>
              <span class="info-value">{{ newsDetail.createTime }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" class="mt-3">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">更新时间：</span>
              <span class="info-value">{{ newsDetail.updateTime }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div v-if="newsDetail.remark" class="info-item">
              <span class="info-label">备注：</span>
              <span class="info-value">{{ newsDetail.remark }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.news-detail-card {
  :deep(.el-card__body) {
    padding: 30px;
  }
}

.news-title {
  font-size: 28px;
  font-weight: bold;
  color: var(--el-text-color-primary);
  line-height: 1.4;
  margin: 0;
}

.news-meta {
  .meta-item {
    color: var(--el-text-color-regular);
    font-size: 14px;
    
    .el-icon {
      color: var(--el-color-primary);
    }
  }
}

.news-stats {
  .stat-item {
    .el-icon {
      color: var(--el-color-primary);
    }
  }
}

.news-cover {
  text-align: center;
  
  .cover-image {
    max-width: 100%;
    max-height: 400px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0;
  padding-bottom: 8px;
  border-bottom: 2px solid var(--el-color-primary);
  display: inline-block;
}

.summary-content {
  font-size: 16px;
  line-height: 1.6;
  color: var(--el-text-color-regular);
}

.content-body {
  font-size: 16px;
  line-height: 1.8;
  color: var(--el-text-color-primary);
  
  :deep(h2) {
    font-size: 22px;
    font-weight: 600;
    margin: 24px 0 16px 0;
    color: var(--el-text-color-primary);
  }
  
  :deep(h3) {
    font-size: 18px;
    font-weight: 600;
    margin: 20px 0 12px 0;
    color: var(--el-text-color-primary);
  }
  
  :deep(p) {
    margin: 12px 0;
    text-align: justify;
  }
  
  :deep(ul), :deep(ol) {
    margin: 12px 0;
    padding-left: 24px;
    
    li {
      margin: 6px 0;
    }
  }
}

.news-extra-info {
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color-light);
  
  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    
    .info-label {
      font-weight: 500;
      color: var(--el-text-color-regular);
      min-width: 80px;
    }
    
    .info-value {
      color: var(--el-text-color-primary);
    }
  }
}

.header-actions {
  display: flex;
  gap: 12px;
}
</style>